//
//  WJLoginViewController.swift
//  WJWeiBo
//
//  Created by wangjun on 16/7/21.
//  Copyright © 2016年 wangjun. All rights reserved.
//

import UIKit
import AFNetworking

class WJLoginViewController: UIViewController {

    override func loadView() {
        //请求
//        https://api.weibo.com/oauth2/authorize?client_id=123050457758183&redirect_uri=http://www.example.com/response&response_type=code

//        //同意授权后会重定向
//        http://www.example.com/response&code=CODE
        
//        https://api.weibo.com/oauth2/authorize
//        client_id	true	string	申请应用时分配的AppKey。
//        redirect_uri	true	string
//
        
          let urlStR = "https://api.weibo.com/oauth2/authorize?client_id=\(WJAPPKEY)&redirect_uri=\(BACK_URL)"
        
        let url = NSURL(string: urlStR)
        
        guard let u = url else{
                
            return
        }
        let request = NSURLRequest(URL: u)

        webView.loadRequest(request)
        
        webView.delegate = self
        view = webView

    }
    
    override func viewWillDisappear(animated: Bool) {
        
        super.viewDidDisappear(animated)

        progress.removeView()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.whiteColor()
           navigationController?.view.insertSubview(progress, belowSubview: navigationController!.navigationBar)
        
        setupUI()
        
    }
    
    func setupUI() {
        
       navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", imgName: nil, target: self, action: "cancelClick")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", imgName: nil, target: self, action: "autoFillClick")
        navigationItem.title = "微博登陆"
        
     
        
    }
  
    @objc private func cancelClick() {
        
        navigationController?.dismissViewControllerAnimated(true, completion: nil)
        
    }
    
  @objc private  func autoFillClick() {
    
        let loginStr = "document.getElementById('userId').value = '\(WJNAME)',document.getElementById('passwd').value = '\(WJWEIBOMIMA)'"
        webView.stringByEvaluatingJavaScriptFromString(loginStr)
    }
    
    //懒加载控件
   private lazy var webView: UIWebView = UIWebView()
    private lazy var progress: WJAutoProgressView = WJAutoProgressView()
    
}

extension WJLoginViewController: UIWebViewDelegate {
    
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
    }
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        
        progress.startAnima()
    }
    //监听请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
    let reqestStr = request.URL?.absoluteString
       
        let query = request.URL?.query

        if let u = reqestStr where u.hasPrefix(BACK_URL) {
            
          let code = query?.substringFromIndex("code=".endIndex)
        
           WJUserAccountViewModel.shareTools.loadUserAccount(code!, isSuccess: { (isSucc) -> () in
            
            
            if !isSucc {
                
                print("失败")
                return
            }
            
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
  
                NSNotificationCenter.defaultCenter().postNotificationName(weiBoSwitchRootVC, object: nil )
            })
 
           })
        }
        
        return true
    }
    
    //结束加载
    func webViewDidFinishLoad(webView: UIWebView) {
        progress.endAnima()
    }

}



